<template>
  <div class="ImageUpload">
    <el-upload
      :class="{disable:fileList.length>0}"
      action="#"
      :file-list="fileList"
      list-type="picture-card"
      :on-preview="preview"
      :on-remove="onRemove"
      :on-change="onChange"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="showProgress"
      :text-inside="true"
      :stroke-width="15"
      :percentage="percentage"
      status="success"
      style="width:160px"
    />
    <el-dialog :visible.sync="dialogVisible" @close="dialogVisible=false">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'

const cos = new COS({
  SecretId: 'AKIDIQHrCG3ZomTwBAsKVQ4RXMvDExQcXAXe',
  SecretKey: 'sUpuiFUTBcleGbfSzGH1VieJhoeDUVFh'
})
console.log(cos)
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      percentage: 0,
      showProgress: false
    }
  },
  methods: {
    preview(file) {
      // 每当点击,都可以获取到当前点击的图片对象
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    onChange(file, fileList) {
      this.fileList = fileList
    },
    beforeUpload(file) {
      if (file.size > 100 * 1024) {
        this.$message.warning('只能上传100k以内的图片')
        return false
      }
      const whiteList = ['image/jpeg', 'image/png', 'image/gif']
      if (!whiteList.includes(file.type)) {
        this.$message.warning('只支持png、gif、jpeg的图片')
        return false
      }
    },
    upload(params) {
      this.showProgress = true
      cos.putObject({
        Bucket: 'test-1307452168', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, // 图片名
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: progressData => { // 上传进度
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          this.fileList[0].url = `http://${data.Location}`
          this.fileList[0].status = 'success'
          setTimeout(() => {
            this.showProgress = false
          }, 1000)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.disable{
  ::v-deep .el-upload--picture-card{
    display: none;
  }
}
.el-progress{
  ::v-deep .el-progress-bar__outer{
    height: 15px;
  }
}

</style>
